'use client';

import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, message, Space, Tag, Divider, Row, Col, Card, Pagination, Select, Spin } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import Layout from '@/components/Layout';
import {
  getInterviewees,
  getResumeById,
  arrangeInterview,
  cancelInterview,
  updateIntervieweeStatus,
  applyOffer,
  deleteInterviewees,
  InterviewStatus,
  getInterviewStatusText,
  generateInterviewEmail,
  generateCancelInterviewEmail,
  generateOfferInstructions,
  type Interviewee,
  getIntervieweeHistory
} from '@/lib/apply';
import { 
  getInterviews, 
  getAllInterviews,
  type InterviewDetail 
} from '@/lib/interview';
import dayjs from 'dayjs';
import { handleResumePreview, downloadFile, cleanupPreviewUrl } from '@/utils/resumeHelper';
import { Document, Page } from 'react-pdf';
import { pdfjs } from 'react-pdf';
import moment from 'moment';
import { styled } from '@mui/material/styles';

const { Option } = Select;

// 设置 PDF.js worker
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

// 修改状态颜色映射的类型定义
interface StatusColorMap {
  [key: number]: string;
}

// 修改状态颜色映射
const STATUS_COLORS: StatusColorMap = {
  [InterviewStatus.Candidate]: 'blue',        // 候选人
  [InterviewStatus.Scheduled]: 'orange',      // 已安排面试
  [InterviewStatus.Interviewing]: 'cyan',     // 面试中
  [InterviewStatus.PendingOffer]: 'gold',     // 待发(面试官已为候选人申请)offer
  [InterviewStatus.OfferSent]: 'purple',      // 已发offer
  [InterviewStatus.OfferAccepted]: 'magenta', // 已接受offer
  [InterviewStatus.Onboard]: 'green',         // 已入职
  [InterviewStatus.Rejected]: 'red',          // 已拒绝
  [InterviewStatus.Blacklist]: 'black',       // 黑名单
  [InterviewStatus.FormalEmployee]: 'lime',   // 正式员工
  [InterviewStatus.Resigned]: 'gray'          // 已离职
};

const CandidatesPage = () => {
  // 状态定义
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<Interviewee[]>([]);
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [form] = Form.useForm();

  // 新增状态
  const [arrangeModalVisible, setArrangeModalVisible] = useState(false);
  const [availableInterviews, setAvailableInterviews] = useState<InterviewDetail[]>([]);
  const [selectedCandidate, setSelectedCandidate] = useState<Interviewee | null>(null);
  const [arrangeForm] = Form.useForm();

  // 添加状态
  const [resumeModalVisible, setResumeModalVisible] = useState(false);
  const [currentResume, setCurrentResume] = useState<any>(null);
  const [resumeLoading, setResumeLoading] = useState(false);
  const [previewUrl, setPreviewUrl] = useState<string>('');
  const [numPages, setNumPages] = useState<number | null>(null);

  // 添加新的状态
  const [historyModalVisible, setHistoryModalVisible] = useState(false);
  const [historyData, setHistoryData] = useState<any[]>([]);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [currentInterviewee, setCurrentInterviewee] = useState<Interviewee | null>(null);
  const [historyPagination, setHistoryPagination] = useState({
    current: 1,
    pageSize: 5,
    total: 0
  });

  // 添加试用期相关状态
  const [tryoutModalVisible, setTryoutModalVisible] = useState(false);
  const [currentTryoutInfo, setCurrentTryoutInfo] = useState<Interviewee | null>(null);

  // 加载数据
  const loadData = async (page = currentPage, size = pageSize) => {
    try {
      setLoading(true);
      const response = await getInterviewees({
        page,
        pageSize: size
      });

      console.log('应聘者列表响应数据:', response);

      if (response.code === 1) {
        // 从 response.data.row 中获取数据
        const interviewees = response.data?.row || [];
        setData(interviewees);
        setTotal(response.data?.total || interviewees.length);

        console.log('处理后的应聘者数据:', {
          total: response.data?.total || interviewees.length,
          pageSize: size,
          currentPage: page,
          records: interviewees
        });
      } else {
        setData([]);
        setTotal(0);
        message.error(response.msg || '获取数据失败');
      }
    } catch (error) {
      console.error('加载数据失败:', error);
      message.error('加载数据失败');
      setData([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 加载可用的面试列表
  const loadAvailableInterviews = async () => {
    try {
      const response = await getAllInterviews({
        page: 1,
        pageSize: 100
      });

      if (response.code === 1) {
        // 添加类型声明
        const futureInterviews = response.data.row.filter(
          (interview: InterviewDetail) => dayjs(interview.startTime).isAfter(dayjs())
        );
        setAvailableInterviews(futureInterviews);
      } else {
        message.error(response.msg || '获取面试列表失败');
      }
    } catch (error) {
      console.error('获取面试列表失败:', error);
      message.error('获取面试列表失败');
    }
  };

  // 处理安排面试
  const handleArrangeInterview = (record: Interviewee) => {
    setSelectedCandidate(record);
    loadAvailableInterviews();
    setArrangeModalVisible(true);
  };

  // 提交面试安排
  const handleArrangeSubmit = async (values: any) => {
    if (!selectedCandidate) return;
    
    try {
      setLoading(true);
      
      // 获取选中的面试详情
      const selectedInterview = availableInterviews.find(
        interview => interview.id === values.interviewId
      );
      
      if (!selectedInterview) {
        message.error('未找到选中的面试安排');
        return;
      }

      // 生成邮件内容
      const emailContent = generateInterviewEmail({
        positionName: selectedInterview.name,
        date: dayjs(selectedInterview.startTime).format('YYYY-MM-DD'),
        time: `${dayjs(selectedInterview.startTime).format('HH:mm')}-${dayjs(selectedInterview.endTime).format('HH:mm')}`,
        location: selectedInterview.place,
        contactPerson: selectedInterview.createBy || '人事部',
        contactPhone: '13800138000' // 这里需要替换为实际的联系电话
      });

      // 发送安排面试请求
      const response = await arrangeInterview({
        interviewId: values.interviewId,
        intervieweeIds: [selectedCandidate.id],
        ...emailContent
      });

      if (response.code === 1) {
        message.success('面试安排成功');
        setArrangeModalVisible(false);
        arrangeForm.resetFields();
        loadData(); // 重新加载候选人列表
      } else {
        message.error(response.msg || '面试安排失败');
      }
    } catch (error) {
      console.error('面试安排失败:', error);
      message.error('面试安排失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理面试取消
  const handleCancelInterview = async (record: Interviewee) => {
    try {
      // 获取当前应聘者的面试安排
      const response = await getAllInterviews({
        page: 1,
        pageSize: 100
      });

      if (response.code !== 1) {
        message.error(response.msg || '获取面试信息失败');
        return;
      }

      // 找到该应聘者最近的一场面试
      const interview = response.data.row.find(
        (interview: InterviewDetail) => 
          interview.intervieweeMsg?.some(
            interviewee => interviewee.id === record.id
          )
      );

      if (!interview) {
        message.error('未找到相关面试安排');
        return;
      }

      // 生成取消面试的邮件内容
      const emailContent = generateCancelInterviewEmail({
        positionName: interview.name,
        originalDate: dayjs(interview.startTime).format('YYYY-MM-DD'),
        originalTime: `${dayjs(interview.startTime).format('HH:mm')}-${dayjs(interview.endTime).format('HH:mm')}`,
        reason: '因特殊原因需要调整面试时间',
        contactPerson: interview.createBy || '人事部',
        contactPhone: '13800138000', // 这里需要替换为实际的联系电话
        willReschedule: true
      });

      // 发送取消面试请求
      const cancelResponse = await cancelInterview({
        interviewId: interview.id,
        intervieweeIds: [record.id],
        ...emailContent
      });

      if (cancelResponse.code === 1) {
        message.success('面试已取消');
        loadData();
      } else {
        message.error(cancelResponse.msg || '取消面试失败');
      }
    } catch (error) {
      console.error('取消面试失败:', error);
      message.error('取消面试失败');
    }
  };

  // 修改状态变更处理函数
  const handleStatusChange = async (record: Interviewee, newStatus: InterviewStatus) => {
    try {
      const response = await updateIntervieweeStatus({
        intervieweeIds: [record.id],  // 改为数组形式
        interviewStatus: newStatus
      });

      if (response.code === 1) {
        message.success('状态更新成功');
        // 更新本地数据而不是重新加载
        setData(prevData => prevData.map(item => 
          item.id === record.id 
            ? { ...item, interviewStatus: newStatus }
            : item
        ));
      } else {
        message.error(response.msg || '状态更新失败');
      }
    } catch (error) {
      console.error('更新状态失败:', error);
      message.error('更新状态失败');
    }
  };

  // 可以添加批量状态更新的函数
  const handleBatchStatusChange = async (ids: number[], newStatus: InterviewStatus) => {
    try {
      const response = await updateIntervieweeStatus({
        intervieweeIds: ids,
        interviewStatus: newStatus
      });

      if (response.code === 1) {
        message.success('批量状态更新成功');
        setSelectedRows([]);  // 清空选中
        // 更新本地数据而不是重新加载
        setData(prevData => prevData.map(item => 
          ids.includes(item.id)
            ? { ...item, interviewStatus: newStatus }
            : item
        ));
      } else {
        message.error(response.msg || '批量状态更新失败');
      }
    } catch (error) {
      console.error('批量更新状态失败:', error);
      message.error('批量更新状态失败');
    }
  };

  // 处理offer申请
  const handleApplyOffer = async (record: Interviewee) => {
    try {
      const instructions = generateOfferInstructions({
        name: record.name,
        position: '前端开发工程师', // 需要从record中获取
        department: '技术部',
        interviewScore: 90,
        specialNote: '技术能力突出，沟通良好'
      });

      const response = await applyOffer({
        intervieweeId: record.id,
        instructions
      });

      if (response.code === 1) {
        message.success('offer申请提交成功');
        loadData();
      } else {
        message.error(response.msg || '申请offer失败');
      }
    } catch (error) {
      console.error('申请offer失败:', error);
      message.error('申请offer失败');
    }
  };

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (!selectedRows.length) {
      message.warning('请选择要删除的记录');
      return;
    }

    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRows.length} 条记录吗？`,
      onOk: async () => {
        try {
          const response = await deleteInterviewees(selectedRows);
          if (response.code === 1) {
            message.success('删除成功');
            setSelectedRows([]);
            loadData();
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  // 添加删除单个候选人的函数
  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条记录吗？',
      onOk: async () => {
        try {
          const response = await deleteInterviewees([id]);
          if (response.code === 1) {
            message.success('删除成功');
            loadData();
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  // 添加查看简历的处理函数
  const handleViewResume = async (id: number) => {
    try {
      setResumeLoading(true);
      const response = await getResumeById(id);
      
      if (response.code === 1) {
        console.log('获取到的简历数据:', response.data);
        
        // 处理预览
        const { previewUrl, fileName, fileType } = handleResumePreview(response.data);
        setPreviewUrl(previewUrl);
        setCurrentResume({ fileName, fileType });
        setResumeModalVisible(true);
      } else {
        message.error(response.msg || '获取简历失败');
      }
    } catch (error) {
      console.error('获取简历失败:', error);
      message.error('获取简历失败');
    } finally {
      setResumeLoading(false);
    }
  };

  // 处理模态框关闭
  const handleModalClose = () => {
    if (previewUrl) {
      cleanupPreviewUrl(previewUrl);
      setPreviewUrl('');
    }
    setResumeModalVisible(false);
  };

  // 组件卸载时清理
  useEffect(() => {
    return () => {
      if (previewUrl) {
        cleanupPreviewUrl(previewUrl);
      }
    };
  }, [previewUrl]);

  // 添加获取面试历史的函数
  const handleViewHistory = async (record: Interviewee, page = 1, pageSize = 5) => {
    try {
      setHistoryLoading(true);
      setCurrentInterviewee(record);
      const response = await getIntervieweeHistory(record.id, page, pageSize);
      
      if (response.code === 1) {
        setHistoryData(response.data.row);
        setHistoryPagination({
          current: page,
          pageSize: pageSize,
          total: response.data.total
        });
        setHistoryModalVisible(true);
      } else {
        message.error(response.msg || '获取面试历史失败');
      }
    } catch (error) {
      console.error('获取面试历史失败:', error);
      message.error('获取面试历史失败');
    } finally {
      setHistoryLoading(false);
    }
  };

  // 修改更新指定应聘者状态的函数
  const updateCandidateStatus = async (interviewId: number) => {
    try {
      // 获取最新的应聘者列表
      const response = await getInterviewees({
        page: currentPage,
        pageSize: pageSize
      });

      if (response.code === 1) {
        console.log('状态更新，获取到的最新数据:', response.data);
        // 直接更新本地数据
        setData(response.data.row);
        setTotal(response.data.total);
      }
    } catch (error) {
      console.error('更新应聘者状态失败:', error);
    }
  };

  // 表格列定义
  const columns: ColumnsType<Interviewee> = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '关联工号',
      dataIndex: 'employeeId',
      key: 'employeeId',
      render: (employeeId: string) => employeeId || '-'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '应聘部门',
      dataIndex: 'deptId',
      key: 'deptId',
    },
    {
      title: '应聘岗位',
      dataIndex: 'positionNumber',
      key: 'positionNumber',
    },
    {
      title: '试用详情',
      key: 'tryoutInfo',
      width: 120,
      align: 'left',
      render: (_, record: Interviewee) => (
        <div style={{ textAlign: 'left' }}>
          <Button 
            type="link" 
            onClick={() => {
              setCurrentTryoutInfo(record);
              setTryoutModalVisible(true);
            }}
            disabled={!record.tryoutStartTime}
            style={{ paddingLeft: 0 }}
          >
            {record.tryoutStartTime ? '查看详情' : '未入职'}
          </Button>
        </div>
      )
    },
    {
      title: '面试状态',
      dataIndex: 'interviewStatus',
      key: 'interviewStatus',
      render: (status: number) => {
        const color = STATUS_COLORS[status] || 'default';
        return (
          <Tag color={color}>
            {getInterviewStatusText(status)}
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_, record: Interviewee) => {
        const status = record.interviewStatus;
        
        return (
          <Space size="small" style={{ justifyContent: 'center', width: '100%' }}>
            {/* 添加查看简历按钮 */}
            <Button
              type="link"
              onClick={() => handleViewResume(record.id)}
            >
              查看简历
            </Button>

            {/* 安排面试按钮 - 只有候选人状态可以安排面试 */}
            <Button 
              type="link" 
              onClick={() => handleArrangeInterview(record)}
              disabled={status !== InterviewStatus.Candidate}
            >
              安排面试
            </Button>

            {/* 取消面试按钮 - 只有已安排面试的可以取消 */}
            <Button 
              size="small" 
              onClick={() => handleCancelInterview(record)}
              disabled={status !== InterviewStatus.Scheduled}
            >
              取消面试
            </Button>

            {/* 申请offer按钮 - 只有候选人状态和面试中可以申请offer */}
            <Button 
              size="small" 
              onClick={() => handleApplyOffer(record)}
              disabled={![InterviewStatus.Candidate, InterviewStatus.Interviewing].includes(status)}
            >
              申请offer
            </Button>

            {/* 拒绝按钮 - 已拒绝、已入职、黑名单状态下不能再拒绝 */}
            <Button 
              size="small" 
              danger 
              onClick={() => handleStatusChange(record, InterviewStatus.Rejected)}
              disabled={[
                InterviewStatus.Rejected,
                InterviewStatus.Onboard,
                InterviewStatus.Blacklist
              ].includes(status)}
            >
              拒绝
            </Button>

            {/* 添加黑名单按钮 */}
            <Button 
              size="small" 
              danger 
              onClick={() => handleStatusChange(record, InterviewStatus.Blacklist)}
              disabled={[
                InterviewStatus.Blacklist,    // 已是黑名单状态不能再操作
                InterviewStatus.Onboard       // 已入职状态不能加入黑名单
              ].includes(status)}
              style={{ 
                backgroundColor: status === InterviewStatus.Blacklist ? '#141414' : undefined,
                borderColor: status === InterviewStatus.Blacklist ? '#141414' : undefined,
                color: status === InterviewStatus.Blacklist ? '#fff' : undefined
              }}
            >
              {status === InterviewStatus.Blacklist ? '已列入黑名单' : '加入黑名单'}
            </Button>

            {/* 删除按钮 */}
            <Button 
              size="small" 
              danger
              onClick={() => handleDelete(record.id)}
            >
              删除
            </Button>

            {/* 添加查看历史按钮 */}
            <Button
              type="link"
              onClick={() => handleViewHistory(record, 1, 5)}
            >
              面试历史
            </Button>
          </Space>
        );
      },
    },
  ];

  // 添加面试历史的表格列定义
  const historyColumns = [
    {
      title: '面试时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '专业技能',
      dataIndex: 'professionalSkills',
      key: 'professionalSkills',
    },
    {
      title: '沟通能力',
      dataIndex: 'communicationSkills',
      key: 'communicationSkills',
    },
    {
      title: '团队协作',
      dataIndex: 'teamworkAbility',
      key: 'teamworkAbility',
    },
    {
      title: '总体评分',
      dataIndex: 'overallRating',
      key: 'overallRating',
    },
    {
      title: '备注',
      dataIndex: 'notes',
      key: 'notes',
      ellipsis: true,
    },
    {
      title: '面试结果',
      dataIndex: 'result',
      key: 'result',
      render: (result: number) => (
        <Tag color={result === 1 ? 'success' : result === 2 ? 'error' : 'default'}>
          {result === 1 ? '通过' : result === 2 ? '不通过' : '待定'}
        </Tag>
      ),
    },
  ];

  // 添加批量操作的工具栏
  const TableToolbar = () => (
    <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
      <Col>
        {selectedRows.length > 0 && (
          <Space>
            <span>已选择 {selectedRows.length} 项</span>
            <Button
              type="primary"
              danger
              onClick={handleBatchDelete}
            >
              批量删除
            </Button>
          </Space>
        )}
      </Col>
      <Col>
        <Input.Search
          placeholder="搜索应聘者..."
          allowClear
          style={{ width: 300 }}
          onSearch={(value) => {
            console.log('搜索关键词:', value);
            // TODO: 添加搜索功能
          }}
        />
      </Col>
    </Row>
  );

  return (
    <Layout>
      <div className="p-4">
        <Card 
          title="应聘者列表" 
          className="rounded-lg"
          bodyStyle={{ paddingBottom: 24 }}
          extra={
            selectedRows.length >= 2 && (
              <Button
                type="primary"
                danger
                onClick={handleBatchDelete}
              >
                批量删除
              </Button>
            )
          }
        >
          <TableToolbar />

          {/* 表格区域 */}
          <Card bodyStyle={{ padding: 0 }}>
            <Table
              rowKey="id"
              columns={columns}
              dataSource={data}
              loading={loading}
              rowSelection={{
                selectedRowKeys: selectedRows,
                onChange: (selectedRowKeys) => {
                  setSelectedRows(selectedRowKeys as number[]);
                },
              }}
              pagination={false}
            />
          </Card>

          {/* 分页区域 */}
          <Row justify="end" style={{ marginTop: 24 }}>
            <Col>
              <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={total}
                onChange={(page, size) => {
                  setCurrentPage(page);
                  setPageSize(size);
                  loadData(page, size);
                }}
                showSizeChanger
                showQuickJumper
                showTotal={(total) => `共 ${total} 条记录`}
                size="default"
              />
            </Col>
          </Row>
        </Card>
      </div>

      {/* 安排面试的模态框 */}
      <Modal
        title="安排面试"
        open={arrangeModalVisible}
        onOk={() => arrangeForm.submit()}
        onCancel={() => {
          setArrangeModalVisible(false);
          arrangeForm.resetFields();
          setSelectedCandidate(null);
        }}
        confirmLoading={loading}
      >
        <Form
          form={arrangeForm}
          layout="vertical"
          onFinish={handleArrangeSubmit}
        >
          <Form.Item
            label="应聘者"
            name="candidateName"
            initialValue={selectedCandidate?.name}
          >
            <Input disabled />
          </Form.Item>

          <Form.Item
            label="选择面试"
            name="interviewId"
            rules={[{ required: true, message: '请选择面试' }]}
          >
            <Select placeholder="请选择面试">
              {availableInterviews.map(interview => (
                <Option key={interview.id} value={interview.id}>
                  {`${interview.name} (${dayjs(interview.startTime).format('MM-DD HH:mm')}~${dayjs(interview.endTime).format('HH:mm')})`}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加简历预览模态框 */}
      <Modal
        title={currentResume?.fileName || '简历预览'}
        open={resumeModalVisible}
        onCancel={handleModalClose}
        footer={[
          <Button 
            key="download" 
            onClick={() => downloadFile(previewUrl, currentResume?.fileName)}
          >
            下载
          </Button>,
          <Button key="close" onClick={handleModalClose}>
            关闭
          </Button>
        ]}
        width={1000}
        bodyStyle={{ maxHeight: '80vh', overflow: 'auto' }}
      >
        <Spin spinning={resumeLoading}>
          {previewUrl && currentResume?.fileType.includes('pdf') ? (
            <Document
              file={previewUrl}
              onLoadSuccess={({ numPages }) => setNumPages(numPages)}
            >
              {Array.from(new Array(numPages), (el, index) => (
                <Page 
                  key={`page_${index + 1}`} 
                  pageNumber={index + 1} 
                  width={800}
                />
              ))}
            </Document>
          ) : previewUrl && currentResume?.fileType.includes('image') ? (
            <img 
              src={previewUrl} 
              style={{ maxWidth: '100%' }} 
              alt="简历预览" 
            />
          ) : (
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <p>Excel文件不支持在线预览，请下载后查看</p>
              <Button 
                type="primary" 
                onClick={() => downloadFile(previewUrl, currentResume?.fileName)}
                style={{ marginTop: '16px' }}
              >
                下载文件
              </Button>
            </div>
          )}
        </Spin>
      </Modal>

      {/* 添加面试历史模态框 */}
      <Modal
        title={`${currentInterviewee?.name || ''} - 面试历史记录`}
        open={historyModalVisible}
        onCancel={() => setHistoryModalVisible(false)}
        footer={null}
        width={1000}
      >
        <Spin spinning={historyLoading}>
          <Table
            columns={historyColumns}
            dataSource={historyData}
            rowKey="id"
            pagination={{
              ...historyPagination,
              onChange: (page, pageSize) => {
                if (currentInterviewee) {
                  handleViewHistory(currentInterviewee, page, pageSize);
                }
              },
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`,
            }}
            size="small"
          />
        </Spin>
      </Modal>

      {/* 添加试用期详情模态框 */}
      <Modal
        title="试用期详情"
        open={tryoutModalVisible}
        onCancel={() => {
          setTryoutModalVisible(false);
          setCurrentTryoutInfo(null);
        }}
        footer={[
          <Button 
            key="close" 
            onClick={() => {
              setTryoutModalVisible(false);
              setCurrentTryoutInfo(null);
            }}
          >
            关闭
          </Button>
        ]}
      >
        {currentTryoutInfo && (
          <div className="space-y-4">
            <div>
              <p className="text-gray-500 mb-1">姓名</p>
              <p className="font-medium">{currentTryoutInfo.name}</p>
            </div>
            <div>
              <p className="text-gray-500 mb-1">试用期开始时间</p>
              <p className="font-medium">
                {currentTryoutInfo.tryoutStartTime ? 
                  currentTryoutInfo.tryoutStartTime.split('T')[0] : 
                  '-'
                }
              </p>
            </div>
            <div>
              <p className="text-gray-500 mb-1">试用期结束时间</p>
              <p className="font-medium">
                {currentTryoutInfo.tryoutEndTime ? 
                  currentTryoutInfo.tryoutEndTime.split('T')[0] : 
                  '-'
                }
              </p>
            </div>
            <div>
              <p className="text-gray-500 mb-1">试用期时长</p>
              <p className="font-medium">{currentTryoutInfo.tryoutDuration || '-'}</p>
            </div>
          </div>
        )}
      </Modal>
    </Layout>
  );
};

export default CandidatesPage;
